package com.slg.android.manyanime.fragment;

;import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.slg.android.manyanime.CartoonDetailActivity;
import com.slg.android.manyanime.R;
import com.slg.android.manyanime.adapter.CartoonHotAdapter;

import com.slg.android.manyanime.bean.CartoonBean;
import com.slg.android.manyanime.utils.NetUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Thinkpad on 2015/3/11.
 */
public class CartoonHotFragment extends Fragment implements PullToRefreshListView.OnRefreshListener2
        , ListView.OnItemClickListener

{
    //
    public static String path =
            "http://manhua.api.61.com/?&pf=1&android_version=16&app_version=512&app_channel=%E7%99%BE%E5%BA%A6&m=Cartoon&a=newIndex&tab=0&page=";
    public String currentPath = path + 1;


    private List<CartoonBean> cartoonBeans;

    @ViewInject(R.id.cartoon_hot_list)
    private PullToRefreshListView refreshListView;
    @ViewInject(R.id.common_loading)
    private RelativeLayout loading;
    @ViewInject(R.id.common_loading_image)
    private ImageView loadingImg;


    private HttpUtils httpUtils;

    private CartoonHotAdapter adapter;
    private ListView trueList;
    private Animation loadAnimation;

    public CartoonHotFragment() {
        super();
    }

    private SharedPreferences preferences;

    private String sharedJSON = "CaroonJson";


    private String jsonStr;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preferences = getActivity().getSharedPreferences("JSON", Context.MODE_PRIVATE);
        jsonStr = preferences.getString("CaroonJson", null);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cartoon_hot, container, false);
        ViewUtils.inject(this, view);

        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        refreshListView.setOnRefreshListener(this);

        trueList = refreshListView.getRefreshableView();
        trueList.setOnItemClickListener(this);


        cartoonBeans = new ArrayList<CartoonBean>();
        adapter = new CartoonHotAdapter(getActivity(), cartoonBeans);
        trueList.setAdapter(adapter);
        httpUtils = new HttpUtils();
        //添加数据
        if (NetUtil.isConnectInternet(getActivity())) {
            loading.setVisibility(View.VISIBLE);
            loadAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_common_rotate);
            loadingImg.startAnimation(loadAnimation);
            addCartoonData(cartoonBeans, currentPath);
        }
        return view;
    }

    //上拉加载和下拉刷新操作
    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {

        addCartoonData(cartoonBeans, path + 1);
        refreshListView.onRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        char c = currentPath.charAt(currentPath.length() - 1);
        int page = Integer.parseInt(String.valueOf(c)) + 1;
        currentPath = path + page;
        addCartoonData(cartoonBeans, currentPath);
        refreshListView.onRefreshComplete();
    }

    /**
     * @param list 数据集合
     * @param url  路径
     */
    public void addCartoonData(final List<CartoonBean> list, String url) {
        httpUtils.send(HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                        //获取结果
                        jsonStr = stringResponseInfo.result;
                        if (jsonStr != null) {

                            try {
                                JSONObject object = new JSONObject(jsonStr);
                                JSONArray lists = object.getJSONArray("list");
                                for (int i = 0; i < lists.length(); i++) {
                                    JSONObject innerCartoon = lists.getJSONObject(i);

                                    CartoonBean cartoon = new CartoonBean();

                                    cartoon.parseJson(innerCartoon);

                                    if (!list.contains(cartoon)) {
                                        list.add(cartoon);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        adapter.notifyDataSetChanged();
                        loading.setVisibility(View.GONE);


                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_LONG).show();
                        if (loading != null) {
                            loading.setVisibility(View.GONE);
                        }
                    }
                }
        );
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //获取listview的header的个数，应为点击的时候header占用了索引
        //真实的位置应该是postion-header
        int truePostion = position - trueList.getHeaderViewsCount();
        Intent intent = new Intent(getActivity(), CartoonDetailActivity.class);
        intent.putExtra("id", cartoonBeans.get(truePostion).getId());
        startActivity(intent);

    }
}
